<?php


/**
 * 微信app支付
 */


use EasyWeChat\Foundation\Application;
use EasyWeChat\Payment\Order;

//发起支付
public static function options()
{
    $wechat = SystemConfigService::more(['pay_routine_appid', 'pay_routine_appsecret', 'wechat_token', 'wechat_encodingaeskey', 'wechat_encode']);
    $payment = SystemConfigService::more(['pay_routine_mchid', 'pay_weixin_client_cert', 'pay_weixin_client_key', 'pay_routine_key', 'pay_weixin_open']);
    $config = [
        'app_id' => isset($wechat['pay_routine_appid']) ? trim($wechat['pay_routine_appid']) : '',
        'secret' => isset($wechat['pay_routine_appsecret']) ? trim($wechat['pay_routine_appsecret']) : '',
        'token' => isset($wechat['wechat_token']) ? trim($wechat['wechat_token']) : '',
        'guzzle' => [
            'timeout' => 10.0, // 超时时间（秒）
            'verify' => false
        ],
    ];
    if (isset($wechat['wechat_encode']) && (int)$wechat['wechat_encode'] > 0 && isset($wechat['wechat_encodingaeskey']) && !empty($wechat['wechat_encodingaeskey']))
        $config['aes_key'] = $wechat['wechat_encodingaeskey'];
    if (isset($payment['pay_weixin_open']) && $payment['pay_weixin_open'] == 1) {

    }
    $config['payment'] = [
        'merchant_id' => trim($payment['pay_routine_mchid']),
        'key' => trim($payment['pay_routine_key']),
        'cert_path' => realpath('.' . $payment['pay_weixin_client_cert']),
        'key_path' => realpath('.' . $payment['pay_weixin_client_key']),
//            'notify_url' => trim(SystemConfigService::get('site_url')) . '/api/wechat/notify'
    ];

    return $config;
}
$options = WechatService::options();
if (empty($options)){
    throw new \Exception('微信配置不存在');
}
$app = new Application($options);
$payment = $app->payment;
$attributes = [
    'trade_type'       => 'APP', // JSAPI，NATIVE，APP...
    'body'             => '付费会员服务',
    'detail'           => '付费会员服务', //我这里是通过订单找到商品详情，你也可以自定义
    'out_trade_no'     => $order['order_id'],
    'total_fee'        => $order['price']*100, //因为是以分为单位，所以订单里面的金额乘以100
    'notify_url'       => sys_config('site_url').'/api/pay/notify/wechatpay', // 支付结果通知网址，如果不设置则会使用配置里的默认地址
    // 'openid'           => '当前用户的 openid', // trade_type=JSAPI，此参数必传，用户在商户appid下的唯一标识，
    // ...
];
$c_order = new Order($attributes);
$result = $payment->prepare($c_order);
if ($result->return_code == 'SUCCESS' && $result->result_code == 'SUCCESS'){
    $prepayId = $result->prepay_id;
    $config = $payment->configForAppPayment($prepayId);
    return app('json')->successful(['orderInfo'=>$config]);
}else{
    throw new \Exception($result->return_msg);
}

//支付回调
$options = WechatService::options();
if (empty($options)){
    \think\facade\Log::error('微信支付配置为空');
}
$app = new Application($options);

$response = $app->payment->handleNotify(function ($notify, $successful) {
    // 用户是否支付成功
    if ($successful) {
        \think\facade\Log::error($notify);
        $res = (new UpgradeTeamService())->upgradeTeam($notify->out_trade_no,3);
        if ($res == true){
            \think\facade\Log::error('微信支付回调成功');
            return true;
        }else{
            return false;
        }
    } else { // 用户支付失败
        return false;
    }
});
\think\facade\Log::error(json_encode($response));
$response->send();